package com.lnj.community.utiles;


import jakarta.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Component
public class MailClient {
    private static final Logger log = org.slf4j.LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender javaMailSender; // 注入邮件发送器

    @Value("${spring.mail.username}")
    private String from;// 发件人

    /**
     * 发送邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    public void sendMail(String to, String subject, String content) {
        try {
            // 创建邮件消息
            MimeMessage message = javaMailSender.createMimeMessage();
            // 设置邮件内容
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom(from); // 设置发件人
            helper.setTo(to); // 设置收件人
            helper.setSubject(subject); // 设置主题
            helper.setText(content, true); // 设置内容，true表示支持HTML格式
            javaMailSender.send(message); // 发送邮件
            log.info("邮件发送成功");
        }catch (Exception e) {
            log.error("发送邮件失败", e);
            e.printStackTrace();
        }

    }
}
